package bigdata;

import java.util.Date;

public class WeightCalculator {

	public static void calculate(VisitData visit) {

		float userScore = 0;
		String visitorType = "";

		float currentWeight = SqlDB.getScore(visit.visitId);
		int numOfTimesAcceptedChatBefore = SqlDB.getRate(visit.visitId);
		float timeOnSiteRate = 0;
		float numberOfVisitsInSiteRate = 0;
		final long SECOND = 1000;
		final long MINUTE = 1000 * 60;
		visit.numOfPageVisitsInGivenTime = 8;
		// user in site is less than 1 minute
		if ((visit.lastIsAlive.getTime() - visit.onSiteSince.getTime()) < MINUTE) {
			visitorType = "NEW";
		} else { // user in site is more than 1 minute
			
			// number of page visits
			if (visit.numOfPageVisitsInGivenTime < UpdateAvergeThread.pageVisitPerMinAvg) {
				userScore += normalize(visit.numOfPageVisitsInGivenTime, 40);
				visitorType += "NORMAL";
			} else if (visit.numOfPageVisitsInGivenTime > UpdateAvergeThread.pageVisitPerMinAvg) {
				userScore += normalize(visit.numOfPageVisitsInGivenTime, 50);
				visitorType += "SEARCH";
			} else if (visit.numOfSearchesInGivenTime > UpdateAvergeThread.searchesPerMinAvg) {
				userScore += normalize(visit.numOfSearchesInGivenTime, 50);
				visitorType += "SEARCH";
			} else if (visit.timeOnCurrentPage > MINUTE) {
				userScore += normalize(visit.timeOnCurrentPage, 50);
				visitorType += "UNSURE_USER";
			}

			if (numOfTimesAcceptedChatBefore >= 0 )
				userScore += normalize(numOfTimesAcceptedChatBefore, 20);
			else
				userScore -= normalize(numOfTimesAcceptedChatBefore, 20);
				
			// Referrer bonus
			if (isImportantPage(visit.referrer)) {
				userScore += 15;
				visitorType += ",REDIRECTED";
			}

			// Location bonus
			if (visit.location != null) {
				if (isImportantPage(visit.location.getCountryName())) {
					userScore += 15;
					visitorType += ",LOCATION";
				}
			}
		}

		visit.type = visitorType;
		visit.score = userScore;
	}

	public static double normalize(double dataToNormalize, int precent) {
		double up = Math.max(0, (Math.pow(Math.E + 3, -1 / dataToNormalize) - (1 / Math.E)));
		double down = (1 - (1 / Math.E));
		double result = up / down * precent;
		return result;
	}

	private static boolean isImportantPage(String page) {
		return false;
	}

	private static boolean isImportantLocation(String page) {
		return false;
	}
}
